package cc.rengu.redp.bizimpl.upmp.service.impl;/*
package cc.rengu.redp.bizimpl.upmp.service.impl;

import cc.rengu.igas.bomp.facade.BompTermManageService;
import cc.rengu.igas.bomp.facade.request.GeneratorTermValidCodeRequest;
import cc.rengu.igas.bomp.facade.request.MPOSInstListQueryRequest;
import cc.rengu.igas.bomp.facade.request.RegisterTermRequest;
import cc.rengu.igas.bomp.facade.response.GeneratorTermValidCodeResponse;
import cc.rengu.igas.bomp.facade.response.MPOSInstListQueryResponse;
import cc.rengu.igas.bomp.facade.response.RegisterTermResponse;
import cc.rengu.igas.bomp.facade.result.Result;
import cc.rengu.redp.bizimpl.constant.UpmpConstant;
import cc.rengu.redp.bizimpl.enums.*;
import cc.rengu.redp.bizimpl.upmp.domain.BTxnLimitCfg;
import cc.rengu.redp.bizimpl.upmp.common.BusinessContainer;
import cc.rengu.redp.bizimpl.upmp.dao.TermInfoMapper;
import cc.rengu.redp.bizimpl.upmp.domain.*;
import cc.rengu.redp.bizimpl.upmp.service.*;
import cc.rengu.redp.bizimpl.upmp.vo.OperationResult;
import cc.rengu.redp.bizimpl.upmp.vo.UpmpUserInfoVO;
import cc.rengu.redp.bizimpl.utils.Common;
import cc.rengu.redp.bizimpl.utils.CommonUtils;
import cc.rengu.redp.bizimpl.utils.DateUtils;
import cc.rengu.redp.bizimpl.utils.GZIPUtils;
import cc.rengu.redp.common.exception.RedpException;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.TransactionCallbackWithoutResult;
import org.springframework.transaction.support.TransactionTemplate;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

*/
/**
 * @author 刘玉亮.LL
 *//*

@Service
public class TermInfoServiceImpl extends ServiceImpl<TermInfoMapper, TermInfo> implements ITermInfoService {
    @Autowired
    private TermInfoDao termInfoDao;

    @Autowired
    private TermModelDao termModelDao;

    @Autowired
    private TermBrandDao termBrandDao;

    @Autowired
    private IBizTmpService bizTmpService;

    @Autowired
    private OrganizationsService organizationsService;

    @Autowired
    private IUpmpPrivilegeCheckService authPrivilegeCheckService;

    @Autowired
    private IUpmpSysParamService upmpSysParamService;

   

    @Autowired
    private MchntBaseQueryDao mchntBaseQueryDao;

    @Autowired
    private OrganizationsService organizationService;

    @Autowired
    private BTxnLimitCfgDao bTxnLimitCfgDao;

    @Autowired
    private TransactionTemplate transactionTemplate;

    @Autowired
    private TermBrandNewService termBrandNewService;

    @Autowired
    private RegionInfoService regionInfoService;

    private static String staticFileUploadDir;

    @Override
    protected BaseDao<TermInfo, String> getEntityDao() {
        return termInfoDao;
    }

    public void upstatus(long id, String status) {
        termInfoDao.update(id, status);
    }

    public void deleteall(long id, String impstatus) {
        termInfoDao.deleteall(id, impstatus);
    }

    public void upreason(long id, String status, String cancelReason) {
        termInfoDao.upreason(id, status, cancelReason);
    }

    public int upimsta(long id, String impStatus, String status) {
        termInfoDao.upStatus(id, impStatus, status);
        return 1;
    }

    public int uprefuse(long id, String impStatus, String status, String appReRea) {
        termInfoDao.uprefuse(id, impStatus, status, appReRea);
        return 1;
    }

    public List<String> findAllmerte() {
        return termInfoDao.findAllmerte();
    }

    public OperationResult saveData(String oprMenuId, String oprMenuName, TermInfo entity, HttpServletRequest request, String webNextUrl) {

        String flag = request.getParameter("optFlag");
        String repayPosFlag = request.getParameter("repayPosFlag");
        java.util.Map<String, Object> result = com.google.common.collect.Maps.newHashMap();
        String lastUpddt = DateUtils.formatDate(new Date(), "yyyy-MM-dd HH:mm:ss.SSS");
         UpmpUserInfoVO user = CommonUtils.getCurrentUser(upmpSysParamService);
        UpmpOrganization org = organizationsService.getOrgByCode(user.getOrgCode(), user.getInstId());
        //  entity.setInstId(user.getInstId());
        //停用时发送短信状态 0:无需发送短信、1:发送成功、2:发送失败
        int isSendSmsSuccess = 0;

        TermInfo oldEntity = null;
        if (!PageOptFlagEnum.OPT_FLAG_ADD.getType().equals(flag)) {
            oldEntity = getEntityDao().getById(entity.getId());
        }

        if (PageOptFlagEnum.OPT_FLAG_ADD.getType().equals(flag)) {
            UpmpPrivilegeCheck privilegeCheck = authPrivilegeCheckService.getPrivilegeCheckByPrivilegeCode(user.getInstId(), "统一支付平台终端信息管理:新增");
            String instId = upmpSysParamService.getById(UpmpConstant.IGAS_DEFAULT_INST_ID).getPrimaryValue();
        // 获取渠道ID：固定20
        String channelId = CommonUtils.getChannelId(upmpSysParamService, instId);
            int length = user.getInstId().length();
            String NO = user.getInstId().substring(length - 3, length) + String.format("%05d", Integer.parseInt(upmpSysSeqService.updateParamValue(BusinessContainer.COMM_PARAM_CODE, BusinessContainer.MachiCd_PREFIX, channelId)));

            entity.setTermNo(NO);

            entity.setId(String.valueOf(System.currentTimeMillis()));
            entity.setOprId(user.getId());
            //        entity.setCrtOrgId(org.getOrgCode());
            entity.setCreateTime(lastUpddt);
            entity.setLastOprId(user.getId());
            entity.setLastUpdateTime(lastUpddt);

            */
/*判断是否开通终端pos代付*//*

            if (BusinessContainer.YES.equals(repayPosFlag)) {
                */
/*保存限额信息*//*

                BTxnLimitCfg bTxnLimitCfg = new BTxnLimitCfg();
                bTxnLimitCfg.setInstId(entity.getInstId());
                bTxnLimitCfg.setLimitType("16");
                bTxnLimitCfg.setLimitInst(entity.getMchntNo() + "|" + entity.getTermNo());
                bTxnLimitCfg.setLimitAcctType("*");
                bTxnLimitCfg.setSingleLimitMaxAmt(entity.getSingleLimitMaxAmt());
                bTxnLimitCfg.setDayLimitAmt(entity.getDayLimitAmt());
                bTxnLimitCfg.setMonthLimitAmt(String.valueOf(Integer.parseInt(entity.getDayLimitAmt()) * 31));
                bTxnLimitCfg.setStatus("Y");
                bTxnLimitCfg.setOprId(user.getId());
                bTxnLimitCfg.setCreateTime(lastUpddt);
                bTxnLimitCfg.setId(null);
                if (null != privilegeCheck && BusinessContainer.YES.equals(privilegeCheck.getChecked())) {
                    bTxnLimitCfg.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_ADD_CHECKING.getType());
                    bTxnLimitCfgDao.save(bTxnLimitCfg);
                    //   bizTmpService.saveBizTmp(bTxnLimitCfg, user, org.getInstId(), BizOprEnum.OPR_ADD.getType(), lastUpddt
                    //           , oprMenuId, oprMenuName, bTxnLimitCfg.getStatus(), bTxnLimitCfg.getAuditStatus(), String.valueOf(bTxnLimitCfg.getId()), webNextUrl,entity.getMchntNo(),null,entity.getTermNo());
                } else {
                    bTxnLimitCfg.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_ADD_PASS.getType());
                    bTxnLimitCfgDao.save(bTxnLimitCfg);
                    bizHisService.saveBizHisNew(bTxnLimitCfg, bTxnLimitCfg, user, org.getInstId(), BizOprEnum.OPR_ADD.getType(), lastUpddt
                            , oprMenuId, oprMenuName, String.valueOf(bTxnLimitCfg.getId()), entity.getMchntNo(), null, entity.getTermNo());
                }

                entity.setPasswordOffsetValue(generatePswdOstVlCode(entity.getInstId()));
            } else {
                entity.setRemainLimitAmt("");
            }
            //
            if (null != privilegeCheck && BusinessContainer.YES.equals(privilegeCheck.getChecked())) {
                entity.setTermStatus(BizDataStatusEnum.STATUS_DRAFT.getType());
                entity.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_ADD_CHECKING.getType());
                this.insertTermInfo(entity);

                bizTmpService.saveBizTmp(entity, user, org.getInstId(), BizOprEnum.OPR_ADD.getType(), lastUpddt
                        , oprMenuId, oprMenuName, entity.getTermStatus(), entity.getAuditStatus(), String.valueOf(entity.getId()), webNextUrl, entity.getMchntNo(), entity.getTermPrintMerName(), entity.getTermNo());
                result.put("id", entity.getId());
            } else {
                entity.setTermStatus(BizDataStatusEnum.STATUS_NORMAL.getType());
                entity.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_ADD_PASS.getType());
                this.insertTermInfo(entity);

                bizHisService.saveBizHisNew(entity, entity, user, org.getInstId(), BizOprEnum.OPR_ADD.getType(), lastUpddt
                        , oprMenuId, oprMenuName, String.valueOf(entity.getId()), entity.getMchntNo(), null, entity.getTermNo());
                result.put("id", entity.getId());
            }
            */
/*将终端库存sn更新为已使用状态*//*

            this.updateTermSn(entity.getInstId(), entity.getSn(), entity.getMchntNo(), entity.getTermNo());
        } else if (PageOptFlagEnum.OPT_FLAG_UPDATE.getType().equals(flag)) {
            String id = request.getParameter("id");
            if (Common.isBlank(id)) {
                 log.error("请求参数(id)异常!");
                return OperationResult.buildFailureResult("请求参数(id)异常!", result);
            }

            UpmpPrivilegeCheck privilegeCheck = authPrivilegeCheckService.getPrivilegeCheckByPrivilegeCode(user.getInstId(), "统一支付平台终端信息管理:修改");
            TermInfo termInfo = termInfoDao.getById(id);
            termInfo.setLastOprId(user.getId());
            termInfo.setLastUpdateTime(lastUpddt);
            if (null != privilegeCheck && BusinessContainer.YES.equals(privilegeCheck.getChecked())) {
                */
/*判断是否开通终端pos代付*//*

                if (BusinessContainer.YES.equals(repayPosFlag)) {
                    List<BTxnLimitCfg> btLimitCfList = bTxnLimitCfgDao.findByPDstChannelInfo(termInfo.getInstId(), "16", termInfo.getMchntNo() + "|" + termInfo.getTermNo());
                    if (Common.isNotBlank(btLimitCfList) && btLimitCfList.size() > 0) {
                        BTxnLimitCfg bTxnLimitCfg = btLimitCfList.get(0);
                        bTxnLimitCfg.setLastOprId(user.getId());
                        bTxnLimitCfg.setLastUpdateTime(lastUpddt);
                        bTxnLimitCfg.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_UPD_CHECKING.getType());
                        bTxnLimitCfgDao.save(bTxnLimitCfg);
                       */
/* BTxnLimitCfg bTxnLimitCfgEt = new BTxnLimitCfg();
                        BeanUtils.copyProperties(bTxnLimitCfg, bTxnLimitCfgEt);
                        bTxnLimitCfgEt.setSingleLimitMaxAmt(entity.getSingleLimitMaxAmt());
                        bTxnLimitCfgEt.setDayLimitAmt(entity.getDayLimitAmt());
                        bizTmpService.saveBizTmp(bTxnLimitCfgEt, user, org.getInstId(), BizOprEnum.OPR_UPDATE.getType(), lastUpddt
                                , oprMenuId, oprMenuName, BizDataStatusEnum.STATUS_DRAFT.getType(), bTxnLimitCfgEt.getAuditStatus(), String.valueOf(bTxnLimitCfgEt.getId()), webNextUrl,termInfo.getMchntNo(),null,termInfo.getTermNo());*//*

                    } else {
                        */
/*新增限额信息*//*

                        BTxnLimitCfg bTxnLimitCfg = new BTxnLimitCfg();
                        bTxnLimitCfg.setInstId(entity.getInstId());
                        bTxnLimitCfg.setLimitType("16");
                        bTxnLimitCfg.setLimitInst(entity.getMchntNo() + "|" + entity.getTermNo());
                        bTxnLimitCfg.setLimitAcctType("*");
                        bTxnLimitCfg.setSingleLimitMaxAmt(entity.getSingleLimitMaxAmt());
                        bTxnLimitCfg.setDayLimitAmt(entity.getDayLimitAmt());
                        bTxnLimitCfg.setMonthLimitAmt(String.valueOf(Integer.parseInt(entity.getDayLimitAmt()) * 31));
                        bTxnLimitCfg.setStatus("Y");
                        bTxnLimitCfg.setOprId(user.getId());
                        bTxnLimitCfg.setCreateTime(lastUpddt);
                        bTxnLimitCfg.setId(null);
                        bTxnLimitCfg.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_ADD_CHECKING.getType());
                        bTxnLimitCfgDao.save(bTxnLimitCfg);
                    }
                    entity.setPasswordOffsetValue(generatePswdOstVlCode(entity.getInstId()));
                } else {
                    entity.setRemainLimitAmt("");
                }

                termInfo.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_UPD_CHECKING.getType());
                entity.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_UPD_CHECKING.getType());
                //BeanUtils.copyProperties(entity, termInfo);
                termInfoDao.save(termInfo);

                //检查临时表是否有数据，如果没用则新增
//                saveBizTmp(cupsInstInfo,user,org.getInstId(),BizOprEnum.OPR_UPDATE.getType(),lastUpddt,oprMenuId,oprMenuName);

                bizTmpService.saveBizTmp(entity, user, org.getInstId(), BizOprEnum.OPR_UPDATE.getType(), lastUpddt
                        , oprMenuId, oprMenuName, BizDataStatusEnum.STATUS_DRAFT.getType(), termInfo.getAuditStatus(), String.valueOf(termInfo.getId()), webNextUrl, entity.getMchntNo(), entity.getTermPrintMerName(), entity.getTermNo());
                result.put("id", termInfo.getId());
            } else {
                */
/*判断是否开通终端pos代付*//*

                if (BusinessContainer.YES.equals(repayPosFlag)) {
                    List<BTxnLimitCfg> btLimitCfList = bTxnLimitCfgDao.findByPDstChannelInfo(termInfo.getInstId(), "16", termInfo.getMchntNo() + "|" + termInfo.getTermNo());
                    if (Common.isNotBlank(btLimitCfList) && btLimitCfList.size() > 0) {
                        BTxnLimitCfg oldBTxnLimitCfg = btLimitCfList.get(0);
                        BTxnLimitCfg bTxnLimitCfg = new BTxnLimitCfg();
                        BeanUtils.copyProperties(oldBTxnLimitCfg, bTxnLimitCfg);
                        bTxnLimitCfg.setSingleLimitMaxAmt(entity.getSingleLimitMaxAmt());
                        bTxnLimitCfg.setDayLimitAmt(entity.getDayLimitAmt());
                        bTxnLimitCfg.setMonthLimitAmt(String.valueOf(Integer.parseInt(entity.getDayLimitAmt()) * 31));
                        bTxnLimitCfg.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_UPD_PASS.getType());
                        bTxnLimitCfgDao.save(bTxnLimitCfg);
                        bizHisService.saveBizHisNew(bTxnLimitCfg, oldBTxnLimitCfg, user, org.getInstId(), BizOprEnum.OPR_UPDATE.getType(), lastUpddt
                                , oprMenuId, oprMenuName, String.valueOf(bTxnLimitCfg.getId()), termInfo.getMchntNo(), null, termInfo.getTermNo());
                    } else {
                        */
/*新增限额信息*//*

                        BTxnLimitCfg bTxnLimitCfg = new BTxnLimitCfg();
                        bTxnLimitCfg.setInstId(entity.getInstId());
                        bTxnLimitCfg.setLimitType("16");
                        bTxnLimitCfg.setLimitInst(entity.getMchntNo() + "|" + entity.getTermNo());
                        bTxnLimitCfg.setLimitAcctType("*");
                        bTxnLimitCfg.setSingleLimitMaxAmt(entity.getSingleLimitMaxAmt());
                        bTxnLimitCfg.setDayLimitAmt(entity.getDayLimitAmt());
                        bTxnLimitCfg.setMonthLimitAmt(String.valueOf(Integer.parseInt(entity.getDayLimitAmt()) * 31));
                        bTxnLimitCfg.setStatus("Y");
                        bTxnLimitCfg.setOprId(user.getId());
                        bTxnLimitCfg.setCreateTime(lastUpddt);
                        bTxnLimitCfg.setId(null);
                        bTxnLimitCfg.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_ADD_CHECKING.getType());
                        bTxnLimitCfgDao.save(bTxnLimitCfg);
                    }
                    entity.setPasswordOffsetValue(generatePswdOstVlCode(entity.getInstId()));
                } else {
                    entity.setRemainLimitAmt("");
                }

                entity.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_UPD_PASS.getType());

                BeanUtils.copyProperties(entity, termInfo);
                termInfoDao.save(termInfo);

                //历史表新增
//                saveBizHis(entity,user,org.getInstId(),BizOprEnum.OPR_UPDATE.getType(),lastUpddt,oprMenuId,oprMenuName);
                bizHisService.saveBizHisNew(termInfo, oldEntity, user, org.getInstId(), BizOprEnum.OPR_UPDATE.getType(), lastUpddt
                        , oprMenuId, oprMenuName, String.valueOf(termInfo.getId()), termInfo.getMchntNo(), null, termInfo.getTermNo());
            }
        } else if (PageOptFlagEnum.OPT_FLAG_STOP.getType().equals(flag)
                || PageOptFlagEnum.OPT_FLAG_USE.getType().equals(flag)
                || PageOptFlagEnum.OPT_FLAG_CANCEL.getType().equals(flag)) {
            String id = request.getParameter("id");
            if (Common.isBlank(id)) {
                 log.error("请求参数(id)异常!");
                return OperationResult.buildFailureResult("请求参数(id)异常!", result);
            }
            TermInfo termInfo = termInfoDao.getById(id);

            if (Common.isBlank(termInfo)) {
                 log.error("根据id没有找到指定数据！");
                return OperationResult.buildFailureResult("根据id没有找到指定数据！", result);
            }

            */
/*判断是否开通终端pos代付*//*

            BTxnLimitCfg bTxnLimitCfg = new BTxnLimitCfg();
            BTxnLimitCfg oldBTxnLimitCfg = new BTxnLimitCfg();
            if (BusinessContainer.YES.equals(repayPosFlag)) {
                List<BTxnLimitCfg> btLimitCfList = bTxnLimitCfgDao.findByPDstChannelInfo(termInfo.getInstId(), "16", termInfo.getMchntNo() + "|" + termInfo.getTermNo());
                if (Common.isNotBlank(btLimitCfList) && btLimitCfList.size() > 0) {
                    oldBTxnLimitCfg = btLimitCfList.get(0);
                    BeanUtils.copyProperties(oldBTxnLimitCfg, bTxnLimitCfg);
                }
            }

            UpmpPrivilegeCheck privilegeCheck = new UpmpPrivilegeCheck();
            String bizOpr = "";
            if (PageOptFlagEnum.OPT_FLAG_STOP.getType().equals(flag)) {
                bizOpr = BizOprEnum.OPR_STOP.getType();
                privilegeCheck = authPrivilegeCheckService.getPrivilegeCheckByPrivilegeCode(user.getInstId(), "统一支付平台终端信息管理:停用");
                if (null != privilegeCheck && BusinessContainer.YES.equals(privilegeCheck.getChecked())) {
                    termInfo.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_STOP_CHECKING.getType());
                    bTxnLimitCfg.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_STOP_CHECKING.getType());
                } else {
                    termInfo.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_STOP_PASS.getType());
                    termInfo.setTermStatus(BizDataStatusEnum.STATUS_STOPED.getType());
                    //终端停用发送短信
                    isSendSmsSuccess = sendSMS(termInfo, result);
                    bTxnLimitCfg.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_STOP_PASS.getType());
                    bTxnLimitCfg.setStatus("N");
                }
            } else if (PageOptFlagEnum.OPT_FLAG_USE.getType().equals(flag)) {

                bizOpr = BizOprEnum.OPR_USE.getType();
                privilegeCheck = authPrivilegeCheckService.getPrivilegeCheckByPrivilegeCode(user.getInstId(), "统一支付平台终端信息管理:启用");
                if (null != privilegeCheck && BusinessContainer.YES.equals(privilegeCheck.getChecked())) {
                    termInfo.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_USE_CHECKING.getType());
                    bTxnLimitCfg.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_USE_CHECKING.getType());
                } else {
                    termInfo.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_USE_PASS.getType());
                    termInfo.setTermStatus(BizDataStatusEnum.STATUS_NORMAL.getType());
                    bTxnLimitCfg.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_USE_PASS.getType());
                    bTxnLimitCfg.setStatus("Y");
                }
            } else if (PageOptFlagEnum.OPT_FLAG_CANCEL.getType().equals(flag)) {

                bizOpr = BizOprEnum.OPR_CANCEL.getType();
                privilegeCheck = authPrivilegeCheckService.getPrivilegeCheckByPrivilegeCode(user.getInstId(), "统一支付平台终端信息管理:注销");
                if (null != privilegeCheck && BusinessContainer.YES.equals(privilegeCheck.getChecked())) {
                    termInfo.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_CANCEL_CHECKING.getType());
                    bTxnLimitCfg.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_CANCEL_CHECKING.getType());
                } else {
                    termInfo.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_CANCEL_PASS.getType());
                    termInfo.setTermStatus(BizDataStatusEnum.STATUS_CANCELED.getType());
                    bTxnLimitCfg.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_CANCEL_PASS.getType());
                    bTxnLimitCfg.setStatus("N");
                }
            }
            termInfo.setLastOprId(user.getId());
            //termInfo.setTermStatus(BizDataStatusEnum.STATUS_CANCELED.getType());
            termInfo.setLastUpdateTime(lastUpddt);
            termInfoDao.save(termInfo);
            */
/*判断是否开通终端pos代付*//*

            if (BusinessContainer.YES.equals(repayPosFlag) && Common.isNotBlank(oldBTxnLimitCfg)) {
                bTxnLimitCfg.setLastOprId(user.getId());
                bTxnLimitCfg.setLastUpdateTime(lastUpddt);
                bTxnLimitCfgDao.save(bTxnLimitCfg);
            }
            if (null != privilegeCheck && BusinessContainer.YES.equals(privilegeCheck.getChecked())) {
                //检查临时表是否有数据，如果没用则新增
//                saveBizTmp(cupsInstInfo,user,org.getInstId(),bizOpr,lastUpddt,oprMenuId,oprMenuName);

                bizTmpService.saveBizTmp(termInfo, user, org.getInstId(), bizOpr, lastUpddt
                        , oprMenuId, oprMenuName, termInfo.getTermStatus(), termInfo.getAuditStatus(), termInfo.getId(), webNextUrl, termInfo.getMchntNo(), termInfo.getTermPrintMerName(), termInfo.getTermNo());
            } else {
                //历史表新增
//                saveBizHis(entity,user,org.getInstId(),bizOpr,lastUpddt,oprMenuId,oprMenuName);
                bizHisService.saveBizHisNew(termInfo, oldEntity, user, org.getInstId(), bizOpr, lastUpddt
                        , oprMenuId, oprMenuName, String.valueOf(termInfo.getId()), termInfo.getMchntNo(), null, termInfo.getTermNo());
                */
/*判断是否开通终端pos代付*//*

                if (BusinessContainer.YES.equals(repayPosFlag) && Common.isNotBlank(oldBTxnLimitCfg)) {
                    bizHisService.saveBizHisNew(bTxnLimitCfg, oldBTxnLimitCfg, user, org.getInstId(), bizOpr, lastUpddt, oprMenuId, oprMenuName, String.valueOf(bTxnLimitCfg.getId()), termInfo.getMchntNo(), null, termInfo.getTermNo());
                }
            }
        } else if (PageOptFlagEnum.OPT_FLAG_CHECK.getType().equals(flag)) {

            String id = request.getParameter("id");
            if (Common.isBlank(id)) {
                 log.error("请求参数(id)异常!");
                return OperationResult.buildFailureResult("请求参数(id)异常!", result);
            }

            //获取临时表数据并转换成实体对象
            BizTmp tmp = bizTmpService.getById(id);
            if (Common.isBlank(tmp)) {
                 log.error("根据id没有找到指定临时表数据！");
                return OperationResult.buildFailureResult("根据id没有找到指定临时表数据！", result);
            }
            String bizdata = "";
            if (null != tmp.getBizData1()) {
                bizdata += tmp.getBizData1();
            }
            if (null != tmp.getBizData2()) {
                bizdata += tmp.getBizData2();
            }
            if (null != tmp.getBizData3()) {
                bizdata += tmp.getBizData3();
            }
            TermInfo termInfoNew = JSON.parseObject(bizdata, TermInfo.class);

            TermInfo termInfo = termInfoDao.getById(id);
            if (Common.isBlank(termInfo) && !BizOprEnum.OPR_ADD.equals(tmp.getBizOpr())) {
                 log.error("根据id没有找到指定数据！");
                return OperationResult.buildFailureResult("根据id没有找到指定数据！", result);
            }

            String opt = request.getParameter("opt");
            if (Common.isBlank(opt)) {
                 log.error("请求参数(opt)异常!");
                return OperationResult.buildFailureResult("请求参数(opt)异常!", result);
            }

            String bizOpr = "";
            BeanUtils.copyProperties(termInfoNew, termInfo);

            */
/*判断是否开通终端pos代付*//*

            BTxnLimitCfg bTxnLimitCfg = new BTxnLimitCfg();
            BTxnLimitCfg oldBTxnLimitCfg = new BTxnLimitCfg();
            if (BusinessContainer.YES.equals(repayPosFlag)) {
                List<BTxnLimitCfg> btLimitCfList = bTxnLimitCfgDao.findByPDstChannelInfo(termInfo.getInstId(), "16", termInfo.getMchntNo() + "|" + termInfo.getTermNo());
                if (Common.isNotBlank(btLimitCfList) && btLimitCfList.size() > 0) {
                    oldBTxnLimitCfg = btLimitCfList.get(0);
                    BeanUtils.copyProperties(oldBTxnLimitCfg, bTxnLimitCfg);
                }
            }

            String approvalRefuseReason = request.getParameter("approvalRefuseReason");
            if (BizDataAuditStatusEnum.AUDIT_STATUS_ADD_CHECKING.getType().equals(termInfo.getAuditStatus())) {
                if (PageOptFlagEnum.OPT_FLAG_PASS.getType().equals(opt)) {
                    termInfo.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_ADD_PASS.getType());
                    termInfo.setTermStatus(BizDataStatusEnum.STATUS_NORMAL.getType());
                    bTxnLimitCfg.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_ADD_PASS.getType());
                } else {
                    termInfo.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_ADD_REJECT.getType());
                    bTxnLimitCfg.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_ADD_REJECT.getType());
                }
                bizOpr = BizOprEnum.OPR_ADD.getType();
            } else if (BizDataAuditStatusEnum.AUDIT_STATUS_CANCEL_CHECKING.getType().equals(termInfo.getAuditStatus())) {
                if (PageOptFlagEnum.OPT_FLAG_PASS.getType().equals(opt)) {
                    termInfo.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_CANCEL_PASS.getType());
                    termInfo.setTermStatus(BizDataStatusEnum.STATUS_CANCELED.getType());
                    bTxnLimitCfg.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_CANCEL_PASS.getType());
                    bTxnLimitCfg.setStatus("N");
                } else {
                    termInfo.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_CANCEL_REJECT.getType());
                    bTxnLimitCfg.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_CANCEL_REJECT.getType());
                }
                bizOpr = BizOprEnum.OPR_CANCEL.getType();
            } else if (BizDataAuditStatusEnum.AUDIT_STATUS_STOP_CHECKING.getType().equals(termInfo.getAuditStatus())) {
                if (PageOptFlagEnum.OPT_FLAG_PASS.getType().equals(opt)) {
                    termInfo.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_STOP_PASS.getType());
                    termInfo.setTermStatus(BizDataStatusEnum.STATUS_STOPED.getType());
                    //终端停用发送短信
                    isSendSmsSuccess = sendSMS(termInfo, result);
                    bTxnLimitCfg.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_STOP_PASS.getType());
                    bTxnLimitCfg.setStatus("N");
                } else {
                    termInfo.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_STOP_REJECT.getType());
                    bTxnLimitCfg.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_STOP_REJECT.getType());
                }
                bizOpr = BizOprEnum.OPR_STOP.getType();
            } else if (BizDataAuditStatusEnum.AUDIT_STATUS_USE_CHECKING.getType().equals(termInfo.getAuditStatus())) {
                if (PageOptFlagEnum.OPT_FLAG_PASS.getType().equals(opt)) {
                    termInfo.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_USE_PASS.getType());
                    termInfo.setTermStatus(BizDataStatusEnum.STATUS_NORMAL.getType());
                    bTxnLimitCfg.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_USE_PASS.getType());
                    bTxnLimitCfg.setStatus("Y");
                } else {
                    termInfo.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_USE_REJECT.getType());
                    termInfo.setTermStatus(BizDataStatusEnum.STATUS_STOPED.getType());
                    bTxnLimitCfg.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_USE_REJECT.getType());
                }
                bizOpr = BizOprEnum.OPR_USE.getType();
            } else if (BizDataAuditStatusEnum.AUDIT_STATUS_UPD_CHECKING.getType().equals(termInfo.getAuditStatus())) {
                if (PageOptFlagEnum.OPT_FLAG_PASS.getType().equals(opt)) {
                    termInfo.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_UPD_PASS.getType());
                    termInfo.setTermStatus(BizDataStatusEnum.STATUS_NORMAL.getType());
                    bTxnLimitCfg.setSingleLimitMaxAmt(termInfo.getSingleLimitMaxAmt());
                    bTxnLimitCfg.setDayLimitAmt(termInfo.getDayLimitAmt());
                    bTxnLimitCfg.setMonthLimitAmt(String.valueOf(Integer.parseInt(termInfo.getDayLimitAmt()) * 31));
                    bTxnLimitCfg.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_UPD_PASS.getType());
                } else {
                    termInfo.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_UPD_REJECT.getType());
                    bTxnLimitCfg.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_UPD_REJECT.getType());
                }
                bizOpr = BizOprEnum.OPR_UPDATE.getType();
            }
            termInfo.setAuditRefuseReason(approvalRefuseReason);
            termInfoDao.save(termInfo);
            */
/*判断是否开通终端pos代付*//*

            if (BusinessContainer.YES.equals(repayPosFlag) && Common.isNotBlank(oldBTxnLimitCfg)) {
                bTxnLimitCfgDao.save(bTxnLimitCfg);
            }
            if (PageOptFlagEnum.OPT_FLAG_PASS.getType().equals(opt)) {
                //审批通过将正式表更新到历史表
                bizHisService.saveBizHisNew(termInfo, oldEntity, user, org.getInstId(), bizOpr, lastUpddt, oprMenuId, oprMenuName, String.valueOf(termInfo.getId()), termInfo.getMchntNo(), null, termInfo.getTermNo());
                */
/*判断是否开通终端pos代付*//*

                if (BusinessContainer.YES.equals(repayPosFlag) && Common.isNotBlank(oldBTxnLimitCfg)) {
                    bizHisService.saveBizHisNew(bTxnLimitCfg, oldBTxnLimitCfg, user, org.getInstId(), bizOpr, lastUpddt, oprMenuId, oprMenuName, String.valueOf(bTxnLimitCfg.getId()), termInfo.getMchntNo(), null, termInfo.getTermNo());
                }
            }
            // 修改临时表的审核状态等字段
            bizTmpService.saveBizTmp(termInfo, user, org.getInstId(), bizOpr, lastUpddt, oprMenuId, oprMenuName, termInfo.getTermStatus(), termInfo.getAuditStatus(), String.valueOf(termInfo.getId()), webNextUrl, entity.getMchntNo(), entity.getTermPrintMerName(), entity.getTermNo());
        }
        result.put("isSendSMS", isSendSmsSuccess);
        return OperationResult.buildSuccessResult("数据保存处理完成", result);
    }

    public void insertTermInfo(TermInfo termInfo) throws RedpException {
        StringBuffer sql = new StringBuffer(" INSERT INTO T_B_TERM_INFO ( ");
        sql.append("ID, ");
        sql.append("INST_ID, ");
        sql.append("MCHNT_NO, ");
        sql.append("TERM_PRINT_MER_NAME, ");
        sql.append("TERM_NO, ");
        sql.append("POS_INST_CD, ");
        sql.append("TERM_TYPE, ");
        sql.append("BRAND_CODE, ");
        sql.append("MODEL_CODE, ");
        sql.append("TERM_MACHINE_COMPANY, ");
        sql.append("START_TIME, ");
        sql.append("TERM_TXN_STAR_WAY, ");
        sql.append("TERM_DEVC_TP, ");
        sql.append("TERM_ADDR_PRVNC, ");
        sql.append("TERM_ADDR_CITY, ");
        sql.append("TERM_ADDR_AREA, ");
        sql.append("SHOP_ATTR, ");
        sql.append("SHOPTIME, ");
        sql.append("SN, ");
        sql.append("CONTACT_NAME, ");
        sql.append("CONTACT_PHONE, ");
        sql.append("LONGITUDE, ");
        sql.append("LATITUDE, ");
        sql.append("EFFECTIVE_RADIUS, ");
        sql.append("IC_DOWN_SIGN, ");
        sql.append("KEY_DOWN_SIGN, ");
        sql.append("TERM_SIGN_STATUS, ");
        sql.append("AUTO_SIGNOUT_FLAG, ");
        sql.append("MPOS_INST_ID, ");
        sql.append("BATHC_SETTLE_NUM, ");
        sql.append("CUPS_REPORT_STATUS, ");
        sql.append("CUPS_REPORT_TIME, ");
        sql.append("CUPS_REFUSE_REASON, ");
        sql.append("AUDIT_REFUSE_REASON, ");
        sql.append("TERM_STATUS, ");
        sql.append("AUDIT_STATUS, ");
        sql.append("CRT_ORG_ID, ");
        sql.append("OPR_ID, ");
        sql.append("CREATE_TIME, ");
        sql.append("LAST_OPR_ID, ");
        sql.append("LAST_UPDATE_TIME, ");
        sql.append("LAST_AUDIT_ID, ");
        sql.append("LAST_AUDIT_TIME, ");
        sql.append("REMAIN_LIMIT_AMT, ");
        sql.append("PASSWORD_OFFSET_VALUE, ");
        sql.append("RESERVE1, ");
        sql.append("RESERVE2, ");
        sql.append("RESERVE3, ");
        sql.append("RESERVE4, ");
        sql.append("RESERVE5, ");
        sql.append("RESERVE6, ");
        sql.append("RESERVE7, ");
        sql.append("RESERVE8, ");
        sql.append("RESERVE9 ");
        sql.append(") VALUES (");
        sql.append(":id, ");
        sql.append(":instId, ");
        sql.append(":mchntNo, ");
        sql.append(":termPrintMerName, ");
        sql.append(":termNo, ");
        sql.append(":posInstCd, ");
        sql.append(":termType, ");
        sql.append(":brandCode, ");
        sql.append(":modelCode, ");
        sql.append(":termMachineCompany, ");
        sql.append(":startTime, ");
        sql.append(":termTxnStarWay, ");
        sql.append(":termDevcTp, ");
        sql.append(":termAddrPrvnc, ");
        sql.append(":termAddrCity, ");
        sql.append(":termAddrArea, ");
        sql.append(":shopAttr, ");
        sql.append(":shoptime, ");
        sql.append(":sn, ");
        sql.append(":contactName, ");
        sql.append(":contactPhone, ");
        sql.append(":longitude, ");
        sql.append(":latitude, ");
        sql.append(":effectiveRadius, ");
        sql.append(":icDownSign, ");
        sql.append(":keyDownSign, ");
        sql.append(":termSignStatus, ");
        sql.append(":autoSignoutFlag, ");
        sql.append(":mposInstId, ");
        sql.append(":bathcSettleNum, ");
        sql.append(":cupsReportStatus, ");
        sql.append(":cupsReportTime, ");
        sql.append(":cupsRefuseReason, ");
        sql.append(":auditRefuseReason, ");
        sql.append(":termStatus, ");
        sql.append(":auditStatus, ");
        sql.append(":crtOrgId, ");
        sql.append(":oprId, ");
        sql.append(":createTime, ");
        sql.append(":lastOprId, ");
        sql.append(":lastUpdateTime, ");
        sql.append(":lastAuditId, ");
        sql.append(":lastAuditTime, ");
        sql.append(":remainLimitAmt, ");
        sql.append(":passwordOffsetValue, ");
        sql.append(":reserve1, ");
        sql.append(":reserve2, ");
        sql.append(":reserve3, ");
        sql.append(":reserve4, ");
        sql.append(":reserve5, ");
        sql.append(":reserve6, ");
        sql.append(":reserve7, ");
        sql.append(":reserve8, ");
        sql.append(":reserve9) ");

        Query query = this.getEntityManager().createNativeQuery(sql.toString());
        query.setParameter("id", termInfo.getId());
        query.setParameter("instId", termInfo.getInstId());
        query.setParameter("mchntNo", termInfo.getMchntNo());
        query.setParameter("termPrintMerName", termInfo.getTermPrintMerName());
        query.setParameter("termNo", termInfo.getTermNo());
        query.setParameter("posInstCd", termInfo.getPosInstCd());
        query.setParameter("termType", termInfo.getTermType());
        query.setParameter("brandCode", termInfo.getBrandCode());
        query.setParameter("modelCode", termInfo.getModelCode());
        query.setParameter("termMachineCompany", termInfo.getTermMachineCompany());
        query.setParameter("startTime", termInfo.getStartTime());
        query.setParameter("termTxnStarWay", termInfo.getTermTxnStarWay());
        query.setParameter("termDevcTp", termInfo.getTermDevcTp());
        query.setParameter("termAddrPrvnc", termInfo.getTermAddrPrvnc());
        query.setParameter("termAddrCity", termInfo.getTermAddrCity());
        query.setParameter("termAddrArea", termInfo.getTermAddrArea());
        query.setParameter("shopAttr", termInfo.getShopAttr());
        query.setParameter("shoptime", termInfo.getShoptime());
        query.setParameter("sn", termInfo.getSn());
        query.setParameter("contactName", termInfo.getContactName());
        query.setParameter("contactPhone", termInfo.getContactPhone());
        query.setParameter("longitude", termInfo.getLongitude());
        query.setParameter("latitude", termInfo.getLatitude());
        query.setParameter("effectiveRadius", termInfo.getEffectiveRadius());
        query.setParameter("icDownSign", termInfo.getIcDownSign());
        query.setParameter("keyDownSign", termInfo.getKeyDownSign());
        query.setParameter("termSignStatus", termInfo.getTermSignStatus());
        query.setParameter("autoSignoutFlag", termInfo.getAutoSignoutFlag());
        query.setParameter("mposInstId", termInfo.getMposInstId());
        query.setParameter("bathcSettleNum", termInfo.getBathcSettleNum());
        query.setParameter("cupsReportStatus", termInfo.getCupsReportStatus());
        query.setParameter("cupsReportTime", termInfo.getCupsReportTime());
        query.setParameter("cupsRefuseReason", termInfo.getCupsRefuseReason());
        query.setParameter("auditRefuseReason", termInfo.getAuditRefuseReason());
        query.setParameter("termStatus", termInfo.getTermStatus());
        query.setParameter("auditStatus", termInfo.getAuditStatus());
        query.setParameter("crtOrgId", termInfo.getCrtOrgId());
        query.setParameter("oprId", termInfo.getOprId());
        query.setParameter("createTime", termInfo.getCreateTime());
        query.setParameter("lastOprId", termInfo.getLastOprId());
        query.setParameter("lastUpdateTime", termInfo.getLastUpdateTime());
        query.setParameter("lastAuditId", termInfo.getLastAuditId());
        query.setParameter("lastAuditTime", termInfo.getLastAuditTime());
        query.setParameter("remainLimitAmt", termInfo.getRemainLimitAmt());
        query.setParameter("passwordOffsetValue", termInfo.getPasswordOffsetValue());
        query.setParameter("reserve1", termInfo.getReserve1());
        query.setParameter("reserve2", termInfo.getReserve2());
        query.setParameter("reserve3", termInfo.getReserve3());
        query.setParameter("reserve4", termInfo.getReserve4());
        query.setParameter("reserve5", termInfo.getReserve5());
        query.setParameter("reserve6", termInfo.getReserve6());
        query.setParameter("reserve7", termInfo.getReserve7());
        query.setParameter("reserve8", termInfo.getReserve8());
        query.setParameter("reserve9", termInfo.getReserve9());

        query.executeUpdate();
    }

    */
/**
     * 法人行(3位) + 5位序列号（序列的初始值保持现有终端号的最大值），每家行的序列号分开
     *
     * @param instId 格式化之前的编码
     * @return
     *//*

    public String generateCode(String instId) {
        String instIdn = instId.substring(instId.length() - 3);
        // 获取渠道ID：固定20
        String instId = upmpSysParamService.getById(UpmpConstant.IGAS_DEFAULT_INST_ID).getPrimaryValue();
        // 获取渠道ID：固定20
        String channelId = CommonUtils.getChannelId(upmpSysParamService, instId);
        // 代理商编码前缀：AG
        String prefix = "";//BusinessContainer.TermInfo_PREFIX;
        // 自动生成一级代码
        String paramCode = BusinessContainer.COMM_PARAM_CODE;
        // 生成序列号
        String seqNum = upmpSysSeqService.updateParamValue(paramCode, "TERM_NO" + instIdn, channelId);
        // 代理商编码
        String result = prefix + instIdn + String.format("%05d", Integer.parseInt(seqNum));
        return result;
    }

    //发送短信
    private int sendSMS(TermInfo termInfo, Map<String, Object> result) {
        //获取商户基本信息
        MchntBaseQuery mchntBaseQuery = mchntBaseQueryDao.findOneByMchntNo(termInfo.getMchntNo());
        if (mchntBaseQuery.getSmsFlag().equals("Y")) {
            String phone = mchntBaseQuery.getMchntContactPhone();
            if (null != phone && !phone.equals("")) {
                //调用短信发送接口
//                System.out.println("==================================发送成功======================================");

            } else {
                result.put("smsMsg", "商户未录入联系人手机号，无法发送停用短信");
                return 2;
            }
        } else {
            //商户基本信息配置不发送短信
            return 0;
        }
        result.put("smsMsg", "商户停用短信发送成功");
        return 1;
    }

    public String getUploadPath() {
        if (staticFileUploadDir == null) {
            ExtPropertyPlaceholderConfigurer dynamicConfigService = (ExtPropertyPlaceholderConfigurer) SpringContextHolder.getBean(ExtPropertyPlaceholderConfigurer.class);
            staticFileUploadDir = dynamicConfigService.getProperty("write_upload_file_dir");
            if (StringUtils.isBlank(staticFileUploadDir)) {
                staticFileUploadDir = PropertiesUtils.findPropertiesKey("/application.properties", "write_upload_file_dir");
                if (StringUtils.isBlank(staticFileUploadDir)) {
                    staticFileUploadDir = WebAppContextInitFilter.getInitedWebContextRealPath();
                }
            }

            if (staticFileUploadDir.endsWith(File.separator)) {
                staticFileUploadDir = staticFileUploadDir.substring(0, staticFileUploadDir.length() - 1);
            }

            log.info("Setup file upload root dir:  {}", staticFileUploadDir);
        }

        return staticFileUploadDir;
    }

    public List<TermInfo> getTermInfoFromXls(String filePath, int maxRecords, Map<String, String> result, String instId, String crtOrgId) throws Exception {
        List<TermInfo> list = new ArrayList<TermInfo>();
        int realRows = 0;
        FileInputStream fis = null;
        try {
            fis = new FileInputStream(filePath);
            if (filePath.endsWith(".xls")) {
                HSSFWorkbook workbook = new HSSFWorkbook(fis); // 2003版本的excel，用.xls结尾.得到工作簿
                HSSFSheet sheet = workbook.getSheetAt(0);
                Row row;
                realRows = CommonUtils.findRealRows(sheet);
                if (maxRecords < realRows) {
                    log.error("导入文件中终端信息记录数超过{}！", maxRecords);
                    throw new RedpException("导入文件中终端信息记录数超过" + maxRecords + "！");
                }
                // 把1行跳过
                for (int i = 1; i <= realRows; i++) {
                    row = sheet.getRow(i);
                    TermInfo termInfo = rowTobean(row, result, i + 1, instId);
                    termInfo.setInstId(instId);
                    termInfo.setCrtOrgId(crtOrgId);
                    list.add(termInfo);
                }
                return list;
            } else if (filePath.endsWith(".xlsx")) {
                XSSFWorkbook workbook = new XSSFWorkbook(fis);
                XSSFSheet sheet = workbook.getSheetAt(0);
                Row row;
                realRows = CommonUtils.findRealRows(sheet);
                if (maxRecords < realRows) {
                    log.error("导入文件中终端信息记录数超过{}！", maxRecords);
                    throw new RedpException("导入文件中终端信息记录数超过" + maxRecords + "！");
                }
                // 把1行跳过
                for (int i = 1; i <= realRows; i++) {
                    row = sheet.getRow(i);
                    TermInfo termInfo = rowTobean(row, result, i + 1, instId);
                    termInfo.setInstId(instId);
                    termInfo.setCrtOrgId(crtOrgId);
                    list.add(termInfo);
                }
                return list;
            }
        } catch (FileNotFoundException e) {
             log.error(e.getMessage());
            return null;
        } catch (IOException e) {
             log.error(e.getMessage());
            return null;
        } finally {
            if (null != fis) {
                fis.close();
            }
        }
        return list;
    }

    private TermInfo rowTobean(Row row, Map<String, String> result, int n, String instId) {
        String uploadErrMsg = "";
         UpmpUserInfoVO user = CommonUtils.getCurrentUser(upmpSysParamService);
        UpmpOrganization org = organizationService.getOrgByCode(user.getOrgCode(), user.getInstId());
        SimpleDateFormat fmtdt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
        String lastUpddt = fmtdt.format(new Date());

        TermInfo termInfo = new TermInfo();
        String mchntNo = getCellValue(row, 0);
        if (StringUtils.isNotBlank(mchntNo)) {
            MchntBaseQuery mchnt = mchntBaseQueryDao.findOneByMchntNo(mchntNo);
            if (null != mchnt) {
                termInfo.setMchntNo(mchnt.getMchntNo());
                termInfo.setTermPrintMerName(mchnt.getMchntName());
                termInfo.setPosInstCd(mchnt.getSignInstId());
                //判断商户是否开通终端代付pos
                Boolean bl = selectMchntRepayPos(mchnt.getMchntNo());
                String singleLimitMaxAmt = getCellValue(row, 19);
                String dayLimitAmt = getCellValue(row, 20);
                String remainLimitAmt = getCellValue(row, 21);
                if (bl) {
                    //开通终端代付pos
                    if (StringUtils.isBlank(singleLimitMaxAmt) || StringUtils.isBlank(dayLimitAmt) || StringUtils.isBlank(remainLimitAmt)) {
                        uploadErrMsg += "商户已开通终端代付pos，请填写终端代付限额信息及可用额度；";
                    }
                    termInfo.setSingleLimitMaxAmt(singleLimitMaxAmt);
                    termInfo.setDayLimitAmt(dayLimitAmt);
                    termInfo.setRemainLimitAmt(remainLimitAmt);
                } else {
                    //未开通终端代付pos
                    if (StringUtils.isNotBlank(singleLimitMaxAmt) || StringUtils.isNotBlank(dayLimitAmt) || StringUtils.isNotBlank(remainLimitAmt)) {
                        uploadErrMsg += "商户未开通终端代付pos，不必填写终端代付限额信息及可用额度；";
                    }
                }
            } else {
                uploadErrMsg += "商户编码错误，商户不存在；";
            }
        } else {
            uploadErrMsg += "商户编码为必填项；";
        }
        String termType = getCellValue(row, 1);
        if (StringUtils.isNotBlank(termType)) {
            termType = termType.substring(0, termType.indexOf("-"));
            termInfo.setTermType(termType);
        } else {
            uploadErrMsg += "终端类型为必填项；";
        }
        String brandCode = getCellValue(row, 2);
        if (StringUtils.isNotBlank(brandCode)) {
            */
/*根据厂商名称查询厂商编号*//*

            List<TermBrandInfo> termBrandLst = termBrandNewService.findbrandByName(brandCode);
            if (null != termBrandLst && termBrandLst.size() > 0) {
                brandCode = termBrandLst.get(0).getBrandCode();
                termInfo.setBrandCode(brandCode);
            } else {
                uploadErrMsg += "终端厂商名称查询编码失败；";
            }
        } else {
            uploadErrMsg += "终端厂商为必填项；";
        }
        String modelCode = getCellValue(row, 3);
        if (StringUtils.isNotBlank(modelCode)) {
            modelCode = modelCode.substring(0, modelCode.indexOf("-"));
            termInfo.setModelCode(modelCode);
        } else {
            uploadErrMsg += "终端型号为必填项；";
        }
        if (Common.isNotBlank(getCellValue(row, 4))) {
            termInfo.setStartTime(getCellValue(row, 4) + " 00:00:00.000");
        }
        if (Common.isNotBlank(getCellValue(row, 5))) {
            String termTxnStarWay = getCellValue(row, 5);
            termTxnStarWay = termTxnStarWay.substring(0, termTxnStarWay.indexOf("-"));
            termInfo.setTermTxnStarWay(termTxnStarWay);
        }
        if (Common.isNotBlank(getCellValue(row, 6))) {
            String termDevcTp = getCellValue(row, 6);
            termDevcTp = termDevcTp.substring(0, termDevcTp.indexOf("-"));
            termInfo.setTermDevcTp(termDevcTp);
        }
        String reserve1 = getCellValue(row, 7);
        if (StringUtils.isNotBlank(reserve1)) {
            reserve1 = reserve1.substring(0, reserve1.indexOf("-"));
            termInfo.setReserve1(reserve1);
        } else {
            uploadErrMsg += "终端地理位置校验方式为必填项；";
        }
        String termAddrPrvnc = getCellValue(row, 8);
        if (StringUtils.isNotBlank(termAddrPrvnc)) {
            */
/*省由中文翻译成数字*//*

            List<RegionInfo> regionInfoLst = regionInfoService.getByName(termAddrPrvnc);
            if (null != regionInfoLst && regionInfoLst.size() > 0) {
                termAddrPrvnc = regionInfoLst.get(0).getRegionCode();
                termInfo.setTermAddrPrvnc(termAddrPrvnc);
            } else {
                uploadErrMsg += "布放实体店-省错误；";
            }
        } else {
            uploadErrMsg += "布放实体店-省为必填项；";
        }
        String termAddrCity = getCellValue(row, 9);
        if (StringUtils.isNotBlank(termAddrCity)) {
            */
/*省由中文翻译成数字*//*

            List<RegionInfo> regionInfoLst = regionInfoService.getByName(termAddrCity);
            if (null != regionInfoLst && regionInfoLst.size() > 0) {
                termAddrCity = regionInfoLst.get(0).getRegionCode();
                termInfo.setTermAddrCity(termAddrCity);
            } else {
                uploadErrMsg += "布放实体店-市错误；";
            }
        } else {
            uploadErrMsg += "布放实体店-市为必填项；";
        }
        String termAddrArea = getCellValue(row, 10);
        if (StringUtils.isNotBlank(termAddrArea)) {
            termAddrArea = termAddrArea.substring(0, termAddrArea.indexOf("-"));
            termInfo.setTermAddrArea(termAddrArea);
        } else {
            uploadErrMsg += "布放实体店-区为必填项；";
        }
        String ShopAttr = getCellValue(row, 11);
        if (StringUtils.isNotBlank(ShopAttr)) {
            termInfo.setShopAttr(ShopAttr);
        } else {
            uploadErrMsg += "布放实体店地址为必填项；";
        }
        String Shoptime = getCellValue(row, 12);
        if (StringUtils.isNotBlank(Shoptime)) {
            Shoptime += " 00:00:00.000";
            termInfo.setShoptime(Shoptime);
        } else {
            uploadErrMsg += "布放实体店时间为必填项；";
        }
        String SN = getCellValue(row, 13);
        if (StringUtils.isNotBlank(SN)) {
            //校验s/n是否已入库
            List<Map> snList = selectTermSn(instId, SN);
            if (null == snList || snList.size() < 1) {
                uploadErrMsg += "S/N未入库，请先入库；";
            }
            termInfo.setSn(SN);
        } else {
            uploadErrMsg += "S/N为必填项；";
        }
        if (Common.isNotBlank(getCellValue(row, 14))) {
            termInfo.setContactName(getCellValue(row, 14));
        }
        if (Common.isNotBlank(getCellValue(row, 15))) {
            termInfo.setContactPhone(getCellValue(row, 15));
        }
        String Longitude = getCellValue(row, 16);
        if (StringUtils.isNotBlank(Longitude)) {
            termInfo.setLongitude(Longitude);
        } else {
            uploadErrMsg += "经度为必填项；";
        }
        String Latitude = getCellValue(row, 17);
        if (StringUtils.isNotBlank(Latitude)) {
            termInfo.setLatitude(Latitude);
        } else {
            uploadErrMsg += "纬度为必填项；";
        }
        String EffectiveRadius = getCellValue(row, 18);
        if (StringUtils.isNotBlank(EffectiveRadius)) {
            termInfo.setEffectiveRadius(EffectiveRadius);
        } else {
            uploadErrMsg += "有效半径（千米）为必填项；";
        }

        if (!"".equals(uploadErrMsg)) {
            uploadErrMsg = "第" + n + "行：" + uploadErrMsg + "</br>";
            result.put("uploadErrMsg", uploadErrMsg);
        }
        termInfo.setTermNo(generateCode(user.getInstId()));
        termInfo.setId(String.valueOf(System.currentTimeMillis()));
        //    termInfo.setInstId(org.getInstId());
        termInfo.setOprId(user.getId());
        //    termInfo.setCrtOrgId(org.getOrgCode());
        termInfo.setCreateTime(lastUpddt);
        termInfo.setLastOprId(user.getId());
        termInfo.setLastUpdateTime(lastUpddt);

        termInfo.setCupsReportStatus("00");
        termInfo.setTermStatus(BusinessContainer.data_sta_00);
        termInfo.setAuditStatus(BusinessContainer.status_01);

        return termInfo;
    }

    private String getCellValue(Row row, int cellNum) {
        Cell cell = row.getCell(cellNum);
        if (cell == null) {
            return null;
        }
        cell.setCellType(Cell.CELL_TYPE_STRING);
        return cell.getStringCellValue();
    }

    @Transactional(rollbackFor = Exception.class)
    public void batchSave(String oprMenuId, String oprMenuName, List<TermInfo> list, HttpServletRequest request, String webNextUrl) {
        transactionTemplate.execute(new TransactionCallbackWithoutResult() {
            @Override
            protected void doInTransactionWithoutResult(TransactionStatus arg0) {
                 UpmpUserInfoVO user = CommonUtils.getCurrentUser(upmpSysParamService);
                UpmpOrganization org = organizationService.getOrgByCode(user.getOrgCode(), user.getInstId());
                SimpleDateFormat fmtdt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
                String lastUpddt = fmtdt.format(new Date());
                //验证数据

                //保存数据
                UpmpPrivilegeCheck privilegeCheck = authPrivilegeCheckService.getPrivilegeCheckByPrivilegeCode(user.getInstId(), "统一支付平台终端信息管理:新增");
                for (TermInfo termInfo : list) {
                    BTxnLimitCfg bTxnLimitCfg = null;
                    if (StringUtils.isNotBlank(termInfo.getSingleLimitMaxAmt()) && StringUtils.isNotBlank(termInfo.getDayLimitAmt()) && StringUtils.isNotBlank(termInfo.getRemainLimitAmt())) {
                        */
/*保存限额信息*//*

                        bTxnLimitCfg = new BTxnLimitCfg();
                        bTxnLimitCfg.setInstId(termInfo.getInstId());
                        bTxnLimitCfg.setLimitType("16");
                        bTxnLimitCfg.setLimitInst(termInfo.getMchntNo() + "|" + termInfo.getTermNo());
                        bTxnLimitCfg.setLimitAcctType("*");
                        bTxnLimitCfg.setSingleLimitMaxAmt(termInfo.getSingleLimitMaxAmt());
                        bTxnLimitCfg.setDayLimitAmt(termInfo.getDayLimitAmt());
                        bTxnLimitCfg.setMonthLimitAmt(String.valueOf(Integer.parseInt(termInfo.getDayLimitAmt()) * 31));
                        bTxnLimitCfg.setStatus("Y");
                        bTxnLimitCfg.setOprId(user.getId());
                        bTxnLimitCfg.setCreateTime(lastUpddt);
                        bTxnLimitCfg.setId(null);
                        termInfo.setPasswordOffsetValue(generatePswdOstVlCode(termInfo.getInstId()));
                    }
                    if (null != privilegeCheck && BusinessContainer.YES.equals(privilegeCheck.getChecked())) {
                        termInfo.setTermStatus(BizDataStatusEnum.STATUS_DRAFT.getType());
                        termInfo.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_ADD_CHECKING.getType());
                        insertTermInfo(termInfo);

                        bizTmpService.saveBizTmp(termInfo, user, org.getInstId(), BizOprEnum.OPR_ADD.getType(), lastUpddt
                                , oprMenuId, oprMenuName, termInfo.getTermStatus(), termInfo.getAuditStatus(), String.valueOf(termInfo.getId()), webNextUrl, termInfo.getMchntNo(), termInfo.getTermPrintMerName(), termInfo.getTermNo());
                        if (null != bTxnLimitCfg) {
                            bTxnLimitCfg.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_ADD_CHECKING.getType());
                            bTxnLimitCfgDao.save(bTxnLimitCfg);
                        }
                    } else {
                        termInfo.setTermStatus(BizDataStatusEnum.STATUS_NORMAL.getType());
                        termInfo.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_ADD_PASS.getType());
                        insertTermInfo(termInfo);

                        bizHisService.saveBizHisNew(termInfo, termInfo, user, org.getInstId(), BizOprEnum.OPR_ADD.getType(), lastUpddt
                                , oprMenuId, oprMenuName, String.valueOf(termInfo.getId()), termInfo.getMchntNo(), null, termInfo.getTermNo());
                        if (null != bTxnLimitCfg) {
                            bTxnLimitCfg.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_ADD_PASS.getType());
                            bTxnLimitCfgDao.save(bTxnLimitCfg);
                            bizHisService.saveBizHisNew(bTxnLimitCfg, bTxnLimitCfg, user, org.getInstId(), BizOprEnum.OPR_ADD.getType(), lastUpddt
                                    , oprMenuId, oprMenuName, String.valueOf(bTxnLimitCfg.getId()), termInfo.getMchntNo(), null, termInfo.getTermNo());
                        }
                    }
                    */
/*将终端库存sn更新为已使用状态*//*

                    updateTermSn(termInfo.getInstId(), termInfo.getSn(), termInfo.getMchntNo(), termInfo.getTermNo());
                }
            }
        });
    }

    private Map<String, String> resuleBuild(int code, String msg, String value) {
        Map<String, String> resule = new HashMap<String, String>();
        if (code > 0) {
            resule.put("status", "success");
        } else {
            resule.put("status", "error");
        }
        resule.put("code", code + "");
        resule.put("msg", msg);
        resule.put("value", value);
        return resule;
    }

    */
/**
     * 生成终端验证码
     *
     * @param termNo
     * @param mchntNo
     * @param expiryTime
     * @param user
     * @param traceNo
     * @param bompTermManageService
     * @return
     *//*

    public OperationResult captcha(String termNo, String mchntNo, String expiryTime, UpmpUserInfoVO user, String traceNo, BompTermManageService bompTermManageService) {
        GeneratorTermValidCodeRequest req = new GeneratorTermValidCodeRequest();
        req.setHeader(CommonUtils.packageBompHeader(traceNo, BompTxnNumEnum.generatorTermValidCode.getType(), user.getInstId()));
        req.setUserId(user.getId());
        req.setMchntNo(mchntNo);
        req.setTermNo(termNo);
        req.setExpiryTime(expiryTime);

        java.util.Map<String, Object> result = com.google.common.collect.Maps.newHashMap();
        logger.info("生成终端验证码" + BompTxnNumEnum.generatorTermValidCode.getDesc() + "请求报文：" + JSON.toJSONString(req));
        try {
            Result<GeneratorTermValidCodeResponse> response = bompTermManageService.generatorTermValidCode(req);
            logger.info("生成终端验证码" + BompTxnNumEnum.generatorTermValidCode.getDesc() + "返回报文：" + JSON.toJSONString(response));
            if (response.isSuccess()) {
                GeneratorTermValidCodeResponse resp = response.getResult();
                if (BusinessContainer.BSPS_SUCCESS.equals(resp.getRespCode())) {
                    result.put("respMsg", resp.getRespDesc());
                    result.put("captcha", resp.getValidCode());
                    logger.info("生成终端验证码" + BompTxnNumEnum.generatorTermValidCode.getDesc() + "生成验证码成功");
                    return OperationResult.buildSuccessResult(BompTxnNumEnum.generatorTermValidCode.getDesc() + "交易成功", result);
                } else {
                    result.put("respCode", resp.getRespCode());
                    result.put("respMsg", resp.getRespDesc());
                     log.error("生成终端验证码" + BompTxnNumEnum.generatorTermValidCode.getDesc() + "交易没有获得返回信息");
                    return OperationResult.buildFailureResult(BompTxnNumEnum.generatorTermValidCode.getDesc() + "失败", result);
                }
            } else {
                result.put("resCode", BusinessContainer.ERROR);
                result.put("resMsg", BompTxnNumEnum.generatorTermValidCode.getDesc() + "没有获得返回报文");
                 log.error("生成终端验证码" + BompTxnNumEnum.generatorTermValidCode.getDesc() + "交易没有获得返回信息");
                return OperationResult.buildFailureResult(BompTxnNumEnum.generatorTermValidCode.getDesc() + "失败", result);
            }
        } catch (Exception e) {
            result.put("resCode", BusinessContainer.ERROR);
            result.put("resMsg", e.getMessage());
             log.error("生成终端验证码：，" + BompTxnNumEnum.generatorTermValidCode.getDesc() + "交易出现异常，异常信息：" + e.getMessage(), e);
            return OperationResult.buildFailureResult(BompTxnNumEnum.generatorTermValidCode.getDesc() + "失败", result);
        }
    }


    */
/**
     * 查询母POS机构列表
     *
     * @param instId
     * @param user
     * @param traceNo
     * @param bompTermManageService
     * @return
     *//*

    public Map<String, Object> mposSelect2List(String instId, UpmpUserInfoVO user, String traceNo, BompTermManageService bompTermManageService) {
        MPOSInstListQueryRequest req = new MPOSInstListQueryRequest();
        req.setHeader(CommonUtils.packageBompHeader(traceNo, BompTxnNumEnum.mposInstListQuery.getType(), user.getInstId()));
        req.setMposInstIndex(instId);
        req.setUserId(user.getId());
        logger.info("查询母POS机构列表" + BompTxnNumEnum.mposInstListQuery.getDesc() + "请求报文：" + JSON.toJSONString(req));
        Map<String, Object> maps = new HashMap<String, Object>();
        try {
            Result<MPOSInstListQueryResponse> response = bompTermManageService.mPOSInstListQuery(req);
            logger.info("查询母POS机构列表" + BompTxnNumEnum.mposInstListQuery.getDesc() + "返回报文：" + JSON.toJSONString(response));
            if (response.isSuccess()) {
                MPOSInstListQueryResponse resp = response.getResult();
                if (BusinessContainer.BSPS_SUCCESS.equals(resp.getRespCode())) {
                    logger.info("查询母POS机构列表" + BompTxnNumEnum.mposInstListQuery.getDesc() + "交易成功");
                    String mposInstList = resp.getMposInstList();
                    String[] split = mposInstList.split(",");
                    Map<String, String> map = new HashMap<String, String>();
                    List<Object> rst = new ArrayList<Object>();
                    for (int i = 0; i < split.length; i++) {
                        map = new HashMap<String, String>();
                        map.put("id", split[i]);
                        map.put("name", split[i]);
                        // map.put("belorgname",mc.getBelOrgName());
                        rst.add(map);
                    }
                    maps.put("results", rst);
                    return maps;
                } else {
                    logger.info("查询母POS机构列表" + BompTxnNumEnum.mposInstListQuery.getDesc() + "交易失败");
                }
            } else {
                 log.error("查询母POS机构列表" + BompTxnNumEnum.mposInstListQuery.getDesc() + "交易没有获得返回信息");
            }
        } catch (Exception e) {
             log.error("查询母POS机构列表：，" + BompTxnNumEnum.mposInstListQuery.getDesc() + "交易出现异常，异常信息：" + e.getMessage(), e);
        }
        return maps;
    }

    */
/**
     * 注册终端设备
     *
     * @param mposInstId
     * @param termNo
     * @param bompTermManageService
     *//*

    public Boolean register(String mposInstId, String termNo, UpmpUserInfoVO user, String traceNo, BompTermManageService bompTermManageService) {
        RegisterTermRequest req = new RegisterTermRequest();
        req.setHeader(CommonUtils.packageBompHeader(traceNo, BompTxnNumEnum.registerTerm.getType(), user.getInstId()));
        req.setMposInstNo(mposInstId);
        req.setPosInstNo(termNo);
        req.setUserId(user.getId());
        logger.info("注册终端设备" + BompTxnNumEnum.registerTerm.getDesc() + "请求报文：" + JSON.toJSONString(req));
        try {
            Result<RegisterTermResponse> response = bompTermManageService.registerTerm(req);
            logger.info("注册终端设备" + BompTxnNumEnum.registerTerm.getDesc() + "返回报文：" + JSON.toJSONString(response));
            RegisterTermResponse resp = response.getResult();
            if (BusinessContainer.BSPS_SUCCESS.equals(resp.getRespCode())) {
                 log.error("注册终端设备" + BompTxnNumEnum.registerTerm.getDesc() + "交易成功");
                return true;
            } else {
                 log.error("注册终端设备" + BompTxnNumEnum.registerTerm.getDesc() + "交易失败");
                return false;
            }
        } catch (Exception e) {
             log.error("注册终端设备：，" + BompTxnNumEnum.registerTerm.getDesc() + "交易出现异常，异常信息：" + e.getMessage(), e);
            return false;
        }
    }

    */
/**
     * 校验商户是否开通pos代付
     *
     * @param mchntNo 商户号
     *//*

    public Boolean selectMchntRepayPos(String mchntNo) {
        try {
            StringBuffer sql = new StringBuffer(" select b.MCHNT_NAME,b.MCHNT_NO from T_B_MCHNT_BASE_INFO b join T_B_MCHNT_PROD_INFO p " +
                    "on b.MCHNT_NO = p.MCHNT_NO and b.MCHNT_NO = :mchntNo and p.BASE_PROD_CODE = '10' ");
            Query query = this.getEntityManager().createNativeQuery(sql.toString());
            query.setParameter("mchntNo", mchntNo);
            List<?> list = query.getResultList();
            if (null != list && list.size() > 0) {
                return true;
            } else {
                return false;
            }
        } catch (Exception e) {
            // TODO: handle exception
             log.error("交易出现异常，异常信息：" + e.getMessage());
            throw new RedpException("交易出现异常，异常信息：" + e.getMessage());
        }
    }

    */
/**
     * 查询入库终端sn
     *
     * @param instId 银行代码
     * @param sn     终端sn
     *//*

    public List<Map> selectTermSn(String instId, String sn) {
        try {
            StringBuffer sql = new StringBuffer("select distinct SN from T_B_DEVICE_INFO where INST_ID = :instId and audit_status not in('00','01','03') and status = '10' ");
            if (StringUtils.isNotBlank(sn)) {
                sql.append("and sn like :sn ");
            }
             UpmpUserInfoVO user = CommonUtils.getCurrentUser(upmpSysParamService);
            if (!user.isAdmin()) {
                String userOrgCodes = GZIPUtils.uncompressToString(user.getUserOrgCodes());
                String orgCodes = userOrgCodes.replaceAll(",", "','");
                orgCodes = "'" + orgCodes + "'";
                sql.append("and CRT_ORG_ID in (" + orgCodes + ") ");
            }
            Query query = this.getEntityManager().createNativeQuery(sql.toString());
            query.setParameter("instId", instId);
            if (StringUtils.isNotBlank(sn)) {
                query.setParameter("sn", "%" + sn + "%");
            }
            query.unwrap(SQLQuery.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
            List<Map> list = query.getResultList();
            return list;
        } catch (Exception e) {
            // TODO: handle exception
             log.error("交易出现异常，异常信息：" + e.getMessage());
            throw new RedpException("交易出现异常，异常信息：" + e.getMessage());
        }
    }

    */
/**
     * 更新入库终端sn为已使用
     *
     * @param instId  银行代码
     * @param sn      终端sn
     * @param mchntNo 关联商户编码
     * @param termNo  关联虚拟终端编号
     *//*

    public void updateTermSn(String instId, String sn, String mchntNo, String termNo) {
        StringBuffer sql = new StringBuffer("update T_B_DEVICE_INFO set status = '11',mchnt_no = '" + mchntNo + "',term_no = '" + termNo + "' where INST_ID = :instId and sn = :sn and audit_status not in('00','01','03') and status = '10' ");
         UpmpUserInfoVO user = CommonUtils.getCurrentUser(upmpSysParamService);
        if (!user.isAdmin()) {
            String userOrgCodes = GZIPUtils.uncompressToString(user.getUserOrgCodes());
            String orgCodes = userOrgCodes.replaceAll(",", "','");
            orgCodes = "'" + orgCodes + "'";
            sql.append("and CRT_ORG_ID in (" + orgCodes + ") ");
        }
        Query query = this.getEntityManager().createNativeQuery(sql.toString());
        query.setParameter("instId", instId);
        query.setParameter("sn", sn);
        query.executeUpdate();
    }

    */
/**
     * 查询终端列表
     *
     * @param termNo 终端号
     *//*

    public List<Map> selectTermInfo(String termNo, String instId) {
        try {
            StringBuffer sql = new StringBuffer("select TERM_NO,TERM_PRINT_MER_NAME from T_B_TERM_INFO where INST_ID = :instId ");
            if (StringUtils.isNotBlank(termNo)) {
                sql.append("and TERM_NO like :termNo or TERM_PRINT_MER_NAME like :termName ");
            }
             UpmpUserInfoVO user = CommonUtils.getCurrentUser(upmpSysParamService);
            if (!user.isAdmin()) {
                String userOrgCodes = GZIPUtils.uncompressToString(user.getUserOrgCodes());
                String[] userOrgCodeArray = userOrgCodes.split(",");
                List<String> userOrgCodeList = Arrays.asList(userOrgCodeArray);
                StringBuffer in = new StringBuffer();
                for (int i = 0; i < userOrgCodeList.size(); i++) {
                    if (i > 0) {
                        in.append(",'" + userOrgCodeList.get(i) + "'");
                    } else {
                        in.append("'" + userOrgCodeList.get(i) + "'");
                    }
                }
                sql.append("and CRT_ORG_ID  in (" + in + ") ");
            }
            Query query = this.getEntityManager().createNativeQuery(sql.toString());
            if (user.isAdmin()) {
                query.setParameter("instId", instId);
            } else {
                query.setParameter("instId", user.getInstId());
            }
            if (StringUtils.isNotBlank(termNo)) {
                query.setParameter("termNo", "%" + termNo + "%");
                query.setParameter("termName", "%" + termNo + "%");
            }
            query.unwrap(SQLQuery.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
            List<Map> list = query.getResultList();
            return list;
        } catch (Exception e) {
            // TODO: handle exception
             log.error("交易出现异常，异常信息：" + e.getMessage());
            throw new RedpException("交易出现异常，异常信息：" + e.getMessage());
        }
    }

    */
/**
     * 法人行(3位) + 6位日期(yyMMdd) + 7位序列号，每家行的序列号分开
     *
     * @param instId 格式化之前的编码
     * @return
     *//*

    public String generatePswdOstVlCode(String instId) {
        // 获取渠道ID：固定20
        String instId = upmpSysParamService.getById(UpmpConstant.IGAS_DEFAULT_INST_ID).getPrimaryValue();
        // 获取渠道ID：固定20
        String channelId = CommonUtils.getChannelId(upmpSysParamService, instId);
        // 自动生成一级代码
        String paramCode = BusinessContainer.COMM_PARAM_CODE;
        // 生成序列号
        String seqNum = upmpSysSeqService.updateParamValue(paramCode, "PSWDOSTVL" + instId, channelId);
        // 代付pos验密偏移值
        String dateStr = new SimpleDateFormat("yyyyMMdd").format(new Date());
        dateStr = dateStr.substring(2);
        String result = instId + dateStr + String.format("%07d", Integer.parseInt(seqNum));
        return result;
    }
}
*/
